package core;

import gitobject.Commit;
import repository.Repository;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Scanner;


public class JitLog {
    /**
     * print jit log
     * @param jitPath
     * @throws IOException
     */
    public static void log(String jitPath) throws Exception {

        try{
            String branchName = JitBranch.getCurBranch().branchName;
            File currBranch= new File(jitPath +File.separator + ".jit" + File.separator + "refs"
                    + File.separator + "heads" + File.separator + branchName);
            Scanner input = new Scanner(currBranch);
            String head = input.nextLine(); // read last commit ID from file

            Commit last = Commit.deserialize(head);
            System.out.println("Current branch: " + branchName);

            while(last != null){

                String[] commitMessage = last.getCommitter().split(" ");
                long time = Long.parseLong(commitMessage[2]);
                Date date = new Date(time); // Convert timestamp to time
                System.out.println("commit " + head + "\nAuthor: "+ commitMessage[0] + " " + commitMessage[1] + "\nDate: " + date + "\n" + last.getMessage() + "\n");


                if(last.getParent()!=null){
                    head = last.getParent();
                    last = last.deserialize(head); // point to the previous commit
                }
                else{

                    break;
                }
            }

        }catch(FileNotFoundException e){ // There is no commit record in the current branch
            System.out.println("fatal: your current branch does not have any commits yet");
        }




    }
}
